package gov.pbc.nn.core.bdf.view;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.uploader.DownloadFile;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileProvider;
import com.bstek.dorado.uploader.annotation.FileResolver;

@Component("deptInit")
public class DeptInit{

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao coreHibernateDao;
	
	@Expose
	public <T> void init() throws Exception {
//		if (true)
//			return;
		// 创建saxReader对象
		SAXReader reader = new SAXReader();
		// 通过read方法读取一个文件 转换成Document对象
		Document document = reader.read(new File(DeptInit.class.getResource(
				"dept.xml").toURI()));
		// 获取根节点元素对象
		Element node = document.getRootElement();

		final List<Element> list1 = new ArrayList<Element>();
		list1.addAll(node.elements());

		this.coreHibernateDao.doInHibernateSession(new ISessionCallback<Void>() {

			@Override
			public Void doInSession(Session session) {
				for (int i = 0; i < list1.size(); i++) {
					Dept dept = new Dept();

					dept.setId(list1.get(i).element("ou").getText());
					dept.setName(list1.get(i).element("name").getText());
					String parentId = list1.get(i)
							.element("PBCSupervisorydepartment").getText();
					dept.setParentId(StringUtils.isEmpty(parentId) ? null
							: parentId);
//					dept.setCode(list1.get(i).element("PBCOrgNumber").getText());
//					dept.setType(Integer.parseInt(list1.get(i)
//							.element("PBCOuType").getText()));
					String[] deptTemp = dept.getName().split("/");
					if (deptTemp[0].contains("支行")){
						int deptLevel = deptTemp.length;
						dept.setDeptLevel(String.valueOf(deptLevel));
					}

					dept.setCompanyId("PBCNN");
					session.save(dept);
				}
				return null;
			}
		});

	}

	@FileProvider
	public DownloadFile getAllDept(Map<String, Object> params)
			throws IOException {
		List<Dept> depts = this.coreHibernateDao
				.doInHibernateSession(new ISessionCallback<List<Dept>>() {

					@Override
					public List<Dept> doInSession(Session session) {
						String hql = "from " + Dept.class.getName();
						return session.createQuery(hql).list();
					}

				});
		DownloadFile df = null;
		try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
			ObjectOutputStream os = new ObjectOutputStream(out);
			os.writeObject(depts);

			ByteArrayInputStream in = new ByteArrayInputStream(
					out.toByteArray());
			df = new DownloadFile("default-all-dept", in);
		}

		return df;
	}

	@Expose
	public void initAllDefaultDept() throws IOException, ClassNotFoundException {
		InputStream in = this.getClass()
				.getResourceAsStream("default-all-dept");
		ObjectInputStream is = new ObjectInputStream(in);
		final List<Dept> depts = (List<Dept>) is.readObject();
		this.coreHibernateDao.doInHibernateSession(new ISessionCallback<Void>() {

			@Override
			public Void doInSession(Session session) {
				String hql = "delete from " + Dept.class.getName();
				int count = session.createQuery(hql).executeUpdate();
				for (Dept dept : depts) {
					session.save(dept);
				}
				return null;
			}

		});
	}

	@FileResolver
	public void initAllDept(UploadFile file, Map<String, Object> params)
			throws IOException, ClassNotFoundException {
		InputStream in = file.getInputStream();
		ObjectInputStream is = new ObjectInputStream(in);
		final List<Dept> depts = (List<Dept>) is.readObject();
		this.coreHibernateDao.doInHibernateSession(new ISessionCallback<Void>() {

			@Override
			public Void doInSession(Session session) {
				String hql = "delete from " + Dept.class.getName();
				int count = session.createQuery(hql).executeUpdate();
				for (Dept dept : depts) {
					session.save(dept);
				}
				return null;
			}

		});
	}
}
